import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

/**
 * JWT 策略
 * 基于 NestJS 官方文档实现
 * 参考: https://docs.nestjs.cn/security/authentication
 */
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('jwt.secret'),
    });
  }

  /**
   * 验证 JWT 载荷
   */
  async validate(payload: any) {
    // 这里可以添加额外的验证逻辑
    // 例如：检查用户是否仍然存在、是否被禁用等
    if (!payload.sub) {
      throw new UnauthorizedException('Invalid token payload');
    }

    return {
      userId: payload.sub,
      username: payload.username,
      roles: payload.roles || [],
      siteId: payload.siteId,
    };
  }
}
